<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Db;

class Index3 extends BaseController
{
    const SHOP_DOMIN    = "https://open-oauth.jrtkqk.com";                             //dev go服务端
    const GET_TOKEN_URL = "/admin/oauth/access_token";         //dev seller端
    const REDIREDCT_URL =  "/admin/applications/app/scottAPPa"; //dev seller端

    const client_id = "3080f011110699ddfecc99ec9332d2a9";
    const client_secret = "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";
    const scope = "read_orders";
    const redirect_uri = 'https://tpoauth.cn1.utools.club/code3';

//    const SHOP_DOMIN = "https://xshoppy.utools.club";    //local go 服务端
//    const GET_TOKEN_URL = "http://scott.seller-backend.com/app/open-clients/generate-token"; //local seller端

    const NONCE = "xxxxxxx";
    
    //data analysis
    public function code()
    {
        $shop = $this->request->get('shop');
        $code = $this->request->get('code');
        $hmac = $this->request->get('hmac');
        $nonce = $this->request->get('state');
        $timestamp = $this->request->get('timestamp');

        //1 校验hmac字段
        if (empty($shop)
            || empty($code)
            || empty($hmac)
            || empty($timestamp)) {
            return "Invalid Parameter";
        }
        //2 校验 nonce
        if ($nonce != self::NONCE) {
            return "Invalid Nonce";
        }

        //3 验证hmac是有效的。HMAC由Shoplazza签名
        //数据库查client_secret
        $client_secret = self::client_secret;
        $query_string = sprintf('code=%s&shop=%s&timestamp=%d', $code, $shop, $timestamp);
        $myHmac = base64_encode(hash_hmac('sha256', $query_string, $client_secret));
        if ($hmac !== $myHmac) {
//            return "Invalid Hmac";
        }

        //4 验证hostname  {store_name}.myshoplaza.com
        $pattern = '/(https|http)\:\/\/[a-zA-Z0-9][a-zA-Z0-9\-]*\.myshopify\.com[\/]?/';
        if (!preg_match($pattern, 'https://'.$shop)) {
            return "Invalid Domain";
        }
//        echo $code;
//        die;
        //发送post请求 , 开始获取token
        $params = [
            'client_id'=>self::client_id,
            'client_secret'=> self::client_secret,
            'grant_type'=>'authorization_code',
            'code'=>   $code,
            'redirect_uri'=> self::redirect_uri,
        ];
        $result = $this->sendRequest("https://".$shop .self::GET_TOKEN_URL, $params);
        pd($result);
        $result = json_decode($result,true);
        pd($result);
        if($result['code'] == 0){
            header('Location: '. $shop.self::REDIREDCT_URL .'');
        }
        exit;
    }

    /**
     * xshoppy嵌入的后台页面
     */
    public function admin(){
        //验证开始
        $shop = $this->request->get('shop');
        $code = $this->request->get('code');
        $hmac = $this->request->get('hmac');
        $timestamp = $this->request->get('timestamp');

//        pd($shop,$code,$hmac,$hmac,$timestamp);
        //1 校验hmac字段
        if (empty($shop)
            || empty($code)
            || empty($hmac)
            || empty($timestamp)) {
            return "Invalid Parameter";
        }

        $client_secret = self::client_secret;
        $query_string = sprintf('code=%s&shop=%s&timestamp=%d', $code, $shop, $timestamp);
        $myHmac = base64_encode(hash_hmac('sha256', $query_string, $client_secret));
        if ($hmac !== $myHmac) {
            return "Invalid Hmac";
        }

        return View::fetch();
    }

    public function refresh(){
        $refresh_token = $this->request->get('refresh_token');
        $shop = $this->request->get('shop');
        $params = [
            'client_id'=>self::client_id,
            'client_secret'=> self::client_secret,
            'grant_type'=>'refresh_token',
            'refresh_token'=> $refresh_token,
            'redirect_uri'=> 'https://tpoauth.cn1.utools.club/code',
        ];

        $result = $this->sendRequest($shop.self::GET_TOKEN_URL, $params);
        $result = json_decode($result['result'],true);
        pd($result);
    }

    /**
     * 请求xshoppy是接口数据
     */
    public function posttest(){
        $url = self::SHOP_DOMIN .'/test';
        $param = [

        ];
        $token = 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ0ZXN0X2NsaWVudF8xIiwiZXhwIjoxNjE5ODQwMDgxLCJzdWIiOiJzY290dCJ9.CjRxxH_GJv87fagxVoqgsJrwa4yYNzleXYXEj2s1EhftY9o8dkCjcCs7EGEhTTeOrmtTpvVjAAebSNsjKNA2tg';

        $result = $this->sendRequest($url,$param,$token);
        echo json_encode($result);
    }



    public function sendRequest($uri, $param = [] , $token='')
    {
        $ch = curl_init();
        $headers = [
            'X-Shopify-Access-Token: ' . $token,
            'Content-Type: application/json',
            'Content-Length: ' . strlen(json_encode($param))
        ];

        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));

        $result = curl_exec($ch);
        $headerInfo = curl_getinfo($ch);
        json_decode($result, true);
        //当json decode未失败时不做切割处理
        if (json_last_error() !== JSON_ERROR_NONE) {
            $result = substr($result, $headerInfo['header_size']);
        }
        curl_close($ch);
        return [
            'header' => $headerInfo,
            'result' => $result
        ];
    }

    public function index()
    {
        $myapp = Db::table('oauth_clients')->where('client_id', 'scott')->find();
        View::assign('scopes', 'All');
        View::assign('redirect_uri', $myapp['redirect_uri']);
        View::assign('nonce', self::NONCE);
        return View::fetch();
    }

    public function install()
    {
        $shop = $this->request->get('shop');
        $redirect_uri = sprintf('https://%s/admin/oauth/authorize?client_id=%s&scope=%s&redirect_uri=%s&state=%s&response_type=code',
            $shop,
            self::client_id,
            self::scope,
            self::redirect_uri,
            self::NONCE
        );
        return redirect($redirect_uri);
    }


    public function lists(){
        $lists = Db::table('sail_shop_applications')->alias('a')
            ->leftJoin('oauth_clients c','c.client_id=a.client_id')
            ->where('a.app_type!=3')
            ->select();
//        pd($lists);
        View::assign('lists', $lists);
        return View::fetch();
    }
}
